//#include<stdio.h>
//#include<string.h>                                                                                                                             
//int main()
//{
//    for(int i = 0; i < 200; i++)
//        printf("error[%d] : %s  \n", i, strerror(i));
//    
//    return 0;
//}
//#include<stdio.h>
//#include<stdlib.h>
//#include<unistd.h>
//#include<sys/types.h>
//#include<sys/wait.h>
//
//int main()
//{
//    pid_t id = fork();
//      
//    if(id == 0) //子进程
//    {
//        int cnt = 5;
//        while(cnt)
//        {
//            printf("child is running, id:%d, ppid:%d\n", getpid(), getppid());
//            sleep(1);
//            cnt--;
//        }
//        exit(1); //子进程退出
//    }
//  
//    int status = 0; //存储子进程退出状态
//    pid_t rid = waitpid(id, &status, 0); //父进程等待 —— 阻塞等待
//    if(rid > 0) //等待成功
//        printf("wait success, status:%d\n", status);
//    else if(rid == -1) //调用失败
//        perror("wait error!\n");                                     
//    
//    return 0;
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
 
#define SIZE 5 

typedef void(*fun_t)(); //函数指针类型
 
fun_t task[SIZE]; //函数指针数组
  
void printlog()
{
    printf("this is a log print task\n");
}
  
void printnet()
{
     printf("this is a net task\n");
}
 
void printNPC()
{
    printf("this is a flush NPC task\n");
}                                                                                                                            
void Inittask()
{
    task[0] = printlog;
    task[1] = printnet; 
    task[2] = printNPC;
    task[3] = NULL;
}

void executeTask()
{
    for(int i = 0; task[i]; i++)
        task[i]();  //回调函数机制
}
 
int main()
{
    Inittask();

    pid_t id = fork(); 

    if(id == 0) //子进程
    {
        int cnt = 2;

        while(cnt)
        {
            printf("I am a process, id:%d, ppid:%d\n", getpid(), getppid());
            sleep(1);
            cnt--;
         }

         exit(1); //子进程退出
      }
  
      int status = 0; //存储子进程退出状态
      
      while(1) //基于非阻塞轮询的访问
      {
        pid_t rid = waitpid(id, &status, WNOHANG); //非阻塞等待
      
        if(rid > 0) //调用成功，收集到了已经结束的子进程
        {
          printf("wait success, status:%d\n", status);
        
          break;
        }
        else if(rid == 0) //调用成功，未收集到已经结束的子进程
        {
            printf("child is running, father do other thing!\n");
            printf("------------ Task begin ----------------\n");
            executeTask(); //等待期间，执行其他任务 
            printf("------------ Task end ----------------\n");
        }
        else //调用失败
        {
            perror("wait error\n");
            break;
        }
          
        sleep(1);
    }
    return 0;
}
//}
//
